package com.ssd.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ssd.entity.BusinessTypeEntity;
import com.ssd.entity.NodeEntity;
import com.ssd.entity.PartnerEntity;
import com.ssd.entity.RegionEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.util.Map;

@Mapper
public interface NodeDao extends BaseMapper<NodeEntity> {

    @Select("<script>" +
            "SELECT n.*, r.id as region_id, r.name as region_name, r.remark as region_remark," +
            "(SELECT COUNT(*) FROM tb_vending_machine v2 WHERE v2.node_id = n.id) AS vm_count ," +
            "(SELECT COUNT(*) FROM tb_node n2 WHERE n2.region_id = r.id)  AS node_count " +
            "FROM tb_node n " +
            "LEFT JOIN tb_region r ON n.region_id = r.id " +
            "<where> " +
            "<if test='regionId != null and regionId != \"\"'> " +
            " AND n.region_id like CONCAT('%', #{regionId}, '%')" +
            "</if> " +
            "<if test='nodeName != null and nodeName != \"\"'> " +
            " AND n.name like CONCAT('%', #{nodeName}, '%')" +
            "</if> " +
            "</where> " +
            "</script>")
    @Results({
            @Result(property="id", column="id"),
            @Result(property="name", column="name"),
            @Result(property="addr", column="addr"),
            @Result(property="areaId", column="area_id"),
            @Result(property="createUserId", column="create_user_id"),
            @Result(property="ownerId", column="owner_id"),
            @Result(property="ownerName", column="owner_name"),
            @Result(property="businessId", column="business_id"),
            @Result(property="regionId", column="region_id"),
            @Result(property="vmCount", column="vm_count"),
            @Result(property="region",
                    column="region_id",
                    javaType=RegionEntity.class,
                    one=@org.apache.ibatis.annotations.One(select="com.ssd.mapper.RegionDao.selectRegionById")),
            @Result(property="nodeCount", column="node_count", javaType=Integer.class),
            @Result(property="partner",
                    column="partner_id",
                    javaType= PartnerEntity.class,
                    one=@org.apache.ibatis.annotations.One(select="com.ssd.mapper.PartnerDao.selectPartnerById")),
            @Result(property="business",
                    column="business_id",
                    javaType= BusinessTypeEntity.class,
                    one=@org.apache.ibatis.annotations.One(select="com.ssd.mapper.BusinessDao.selectBusinessById"))
    })
    Page<Map<String, Object>> selectNodeList(Page<?> page,Long regionId,String nodeName);
}